<?php

namespace App\Console\Commands;

use App\Helpers\ConfigTrait;
use App\Models\Order;
use App\Service\ConfigService;
use App\User;
use Carbon\Carbon;
use Illuminate\Console\Command;

class AutoReceipt extends Command
{
    use ConfigTrait;
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'auto:receipt';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '自动收货';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $config = app(ConfigService::class);
        $shippedDay = $config->getAutoReceiptDay();
        Order::query()->chunk(100, function ($item) use ($shippedDay) {

            foreach ($item as $value) {
                $data = $value->extra;
                if (isset($data['attach'])) {
                    $member_id = json_decode($data['attach'], true)['member_id'];
                    $shared = User::find($member_id);
                } else {
                    $shared = null;
                }
                dispatch(new \App\Jobs\AutoReceipt($value->id, $shippedDay, $shared));
            }
        });
        echo '运行成功';
    }
}
